/*
 * @Author: song
 * @Description:窗口绘制基类
 * @Date: 2024年04月23日 星期二 14:04:31
 * @Modify:
 */

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace SCore.Editor.WindowDraw
{
    public abstract class IEditorWindow : EditorWindow
    {
        private List<ICommonView> _commonViews = new List<ICommonView>();
        private Dictionary<int, IESubWindow> _windowViews = new Dictionary<int, IESubWindow>();

        public virtual void OnEnable()
        {
            var bindWindows = BindWindow();
            if (bindWindows != null)
            {
                _windowViews = bindWindows;
            }

            var bindViews = BindView();
            if (bindViews != null)
            {
                _commonViews.AddRange(BindView());
            }

            //subWin enable
            foreach (var view in _windowViews)
            {
                view.Value.OnEnable();
            }

            //commonView enable
            foreach (var view in _commonViews)
            {
                view.OnEnable();
            }

            EditorApplication.update += OnEditorUpdate;
        }

        public virtual void OnDisable()
        {
            foreach (var view in _windowViews)
            {
                view.Value.OnDisable();
            }

            _windowViews = null;
            foreach (var view in _commonViews)
            {
                view.OnDisable();
            }

            _commonViews = null;
            EditorApplication.update -= OnEditorUpdate;
        }

        public virtual void OnGUI()
        {
            Event e = Event.current;

            foreach (var commonView in _commonViews)
            {
                commonView.UpdateEvent(e);
                commonView.OnGUI();
            }

            foreach (var commonView in _windowViews)
            {
                commonView.Value.UpdateEvent(e);
            }

            if (e.keyCode == KeyCode.Escape)
            {
                GUI.FocusControl(null);
                Repaint();
            }
        }

        private void OnEditorUpdate()
        {
            Repaint();
            foreach (var view in _windowViews)
            {
                view.Value.Update();
            }

            foreach (var view in _commonViews)
            {
                view.Update();
            }
        }


        protected virtual Dictionary<int, IESubWindow> BindWindow()
        {
            return null;
        }

        protected virtual List<ECommonView> BindView()
        {
            return null;
        }

        //public
        public IESubWindow GetWindowView(int index)
        {
            return _windowViews[index];
        }

        public ICommonView GetCommonView(int index)
        {
            return _commonViews[index];
        }
    }
}